package com.yanfei.zero.infrastructure.db;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;

import com.yanfei.zero.application.handler.perms.ICmResourceService;
import com.yanfei.zero.domain.user.model.perms.CmResource;
import com.yanfei.zero.domain.user.repository.CmResourceMapper;
import com.yanfei.zero.domain.user.repository.CmResourceRepository;
import com.yanfei.zero.domain.user.repository.RolePermMapper;

import jakarta.annotation.Resource;
@Service
public class CmResourceService implements ICmResourceService {
	@Resource
	private RolePermMapper rolePermMapper;
	@Resource
	private CmResourceMapper cmResourceMapper;
	@Resource
	private CmResourceRepository cmResourceRepository;
	@Override
	public Set<String> getAllPaths() {
		List<CmResource> lst = rolePermMapper.listAllResource(null);
		Set<String> set = lst.stream().map(it->it.getPath()).collect(Collectors.toSet());
		return set;
	}

	@Override
	public Set<String> getPathsByUserId(String string) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void deleteResourceByType(int i) {
		 CmResource res = new  CmResource();
		 res.setId(i);
		cmResourceRepository.delete(res);
	}

	@Override
	public void insertResources(List<CmResource> list) {
		cmResourceRepository.saveAll(list);
	}

	@Override
	public List<CmResource> getTree() {
		return rolePermMapper.getChildrenByParentId(1000l);
	}
	public List<CmResource> getTree2() {
		List<CmResource> root = new ArrayList<CmResource>();
		// 一次性查出所有节点
		List<CmResource> ress = rolePermMapper.listAllResource(1000l);
        Map<Long, CmResource> nodesMap = ress.stream().collect(Collectors.toMap(CmResource::getId, Function.identity()));
        // 得到树形结构
        for (CmResource data : ress) {
            Long parentId = data.getParentId();

            if (parentId != 1000) {
                CmResource parentNode = nodesMap.get(parentId);
                if (parentNode != null) {
                    parentNode.getChildren().add(data);
                }
            }else {
            	root.add(data);
            }
        }
        
        return root;
	}

}
